package com.yihaodian.search.grouping;

import java.util.List;
import java.util.PriorityQueue;

import com.google.common.collect.Lists;
import com.yihaodian.api.search.misc.SearchHit;

public class HitMerger {
	static class Element implements Comparable<Element> {
		SearchHit[] hits;

		SearchHit hit = null;
		int idx = 0;
		int size = 0;

		Element(SearchHit[] hits) {
			this.hits = hits;

			this.size = hits.length;
			this.hit = hits[idx];
		}

		public boolean next() {
			idx++;
			if (idx >= size)
				return false;

			this.hit = hits[idx];
			return true;
		}

		@Override
		public int compareTo(Element o) {
			/**
			 * Compare order:
			 * 1.SortFields; 2.score; 3.docId
			 */
			float sub = 0;
			
			sub = hit.getScore() - o.hit.getScore();
			
			if (sub == 0) {
				return hit.getDocId() - o.hit.getDocId();
			} else {
				return sub > 0 ? 1 : -1;
			}
		}
	}
	
	public static SearchHit[] merge(SearchHit[] hits1, SearchHit[] hits2){
		/**
		 * group1
		 * aa [doc1, doc2]
		 * bb [doc3, doc4]
		 * 
		 * group2
		 * aa [doc11]
		 * cc [doc22]
		 */
		PriorityQueue<Element> queue = new PriorityQueue<Element>();
		
		int totalHit = hits1.length + hits2.length;
		Element element = new Element(hits1);
		queue.add(element);
		element = new Element(hits2);
		queue.add(element);


		List<SearchHit> hits = Lists.newArrayList();
		for (int i = 0; i < totalHit; i++) {
			Element e = queue.poll();
			hits.add(e.hit);

			if (e.next())
				queue.add(e);
		}

		return hits.toArray(new SearchHit[0]);
	}
}
